﻿using System;
using System.Threading;

/*
 * User: RSny
 * Date: 5/10/2012
 * Time: 12:52 PM
 */

namespace Aspects.Custom.Audio
{
    public abstract class WaveFunction
    {
        public void AllocateBuffers(int bufferSize, int bufferCount)
        {
            FreeBuffers();
//            if (bufferCount > 0)
//            {
//                Buffers = new WaveBuffer(WavePointer, bufferSize);
//                WaveBuffer Prev = Buffers;
//                try
//                {
//                    for (int i = 1; i < bufferCount; i++)
//                    {
//                        WaveBuffer Buf = new WaveBuffer(WavePointer, bufferSize);
//                        Prev.NextBuffer = Buf;
//                        Prev = Buf;
//                    }
//                }
//                finally
//                {
//                    Prev.NextBuffer = Buffers;
//                }
            //}
        }
        
        public void FreeBuffers()
        {
            CurrentBuffer = null;
            if (Buffers != null)
            {
                WaveBuffer First = Buffers;
                Buffers = null;

                WaveBuffer Current = First;
                do
                {
                    WaveBuffer Next = Current.NextBuffer;
                    Current.Dispose();
                    Current = Next;
                } while(Current != First);
            }
        }
        
        public void Advance()
        {
            CurrentBuffer = CurrentBuffer == null ? Buffers : CurrentBuffer.NextBuffer;
            CurrentBuffer.WaitFor();
        }
        
        public void WaitForAllBuffers()
        {
            while (Buffers.NextBuffer != Buffers)
            {
                Buffers.WaitFor();
                Buffers = Buffers.NextBuffer;
            }
        }
                
        public IntPtr WavePointer;
        public WaveBuffer Buffers;
        public WaveBuffer CurrentBuffer;
        public Thread BufferThread;
        public bool Finished;
    }
}